package com.ray.export.runner.exports;

import com.ray.export.empty.Empty;
import com.ray.export.runner.Runner;
import com.ray.export.runner.RunnerResult;
import com.ray.export.spring.ApplicationContextUtil;
import com.ray.export.strategy.data.DataModel;
import com.ray.export.strategy.exports.PageVerification;
import com.ray.export.strategy.exports.PageVerificationResult;
import com.ray.export.strategy.file.FileVerification;
import com.ray.export.template.ExportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * <p>ClassName:     PageVerificationRunner
 * <p>Description:   分页校验执行者
 * <p>Author         jumWang
 * <p>Version        V1.0
 * <p>Date           2019.12.3
 */
@Slf4j
public class PageVerificationRunner implements Runner<ExportTemplate> {

    @Override
    public RunnerResult doRunner(ExportTemplate annotation, DataModel dataModel, RunnerResult perResult) {
        log.info("执行分页校验操作");
        Class<?> pageVerificationClass = annotation.pageVerification();
        if (pageVerificationClass == Empty.class) {
            return new RunnerResult(Empty.class, dataModel,dataModel.getBeforeResult());
        }
        //判读配置是否符合规则
        if (!PageVerification.class.isAssignableFrom(pageVerificationClass)) {
            log.error("分页校验操作配置错误");
            throw new RuntimeException("分页校验操作配置错误");
        }
        //获取执行对象
        PageVerification pageVerification = (PageVerification) ApplicationContextUtil.getApplicationContext().getBean(pageVerificationClass);
        if (ObjectUtils.isEmpty(pageVerification)) {
            log.error("获取执行对象异常[{}]", pageVerificationClass.getName());
            throw new RuntimeException("获取执行对象异常");
        }
        //分页校验
        PageVerificationResult pageVerificationResult = pageVerification.pageVerification(dataModel.getCount());
        if (ObjectUtils.isEmpty(pageVerificationResult)) {
            log.error("分页校验操作失败");
            throw new RuntimeException("分页校验操作失败");
        }
        if(0 >= pageVerificationResult.getPageSize()) {
            log.error("分页大小必须大于0");
            throw new RuntimeException("分页大小必须大于0");
        }
        dataModel.setIsPaging(pageVerificationResult.getIsPaging());
        dataModel.setPageSize(pageVerificationResult.getPageSize());
        return new RunnerResult(FileVerification.class, dataModel, pageVerificationResult);
    }

}
